package service

import (
	"context"
	"database/sql"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/knowledgePoint/glb"
	"google.golang.org/grpc/metadata"
	"gorm.io/gorm"
)

func (s *Service) DeleteKnowledgePoint(ctx context.Context, request *pb.DeleteKnowledgePointRequest) (*pb.DeleteKnowledgePointResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.DeleteKnowledgePointResponse{Status: &pb.ResponseStatus{
			Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
		}}, nil
	}

	knowledgePoint := &models.KnowledgePoint{UUID: request.GetUUID()}

	if token.IsManager {
		manager := &models.UserModel{
			AccountID: token.AccountID,
			Type:      sql.NullInt32{Int32: core.UserTypeManager, Valid: true},
		}
		err = glb.DB.Take(manager, manager).Error
		if err != nil {
			if err == gorm.ErrRecordNotFound {
				return &pb.DeleteKnowledgePointResponse{Status: &pb.ResponseStatus{
					Code:    pb.ResponseStatusCode_NotAuth,
					Message: "用户没有权限",
				}}, nil
			}
			glb.Logger.Error(err.Error())
			return deleteKnowledgePointRespSvrErr, nil
		}
	} else {
		managerUUID := ""
		err = glb.DB.Raw(
			`select course_manager_bind.manager_uuid from course_manager_bind
				where course_manager_bind.course_uuid = (
					select course_model.uuid from chapter_model
					join course_model on course_model.uuid = chapter_model.course_uuid
					where chapter_model.uuid = ?
				) and course_manager_bind.manager_id = ? `, knowledgePoint.ChapterUUID, token.AccountID,
		).Scan(&managerUUID).Error
		if err != nil {
			glb.Logger.Error(err.Error())
			return deleteKnowledgePointRespSvrErr, nil
		}
		if managerUUID == "" {
			return &pb.DeleteKnowledgePointResponse{Status: &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_OtherError,
				Message: "用户没有权限",
			}}, nil
		}
	}

	err = glb.DB.Delete(knowledgePoint).Error
	if err != nil {
		glb.Logger.Error(err.Error())
		return deleteKnowledgePointRespSvrErr, nil
	}

	return &pb.DeleteKnowledgePointResponse{
		Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_Success},
	}, nil
}
